version: '3.8'
services:
  db:
    image: mongo
    container_name: mongodb
    command: mongod --replSet rs0
    restart: unless-stopped
    ports:
      - 27017:27017
    volumes:
      - db-data:/data
  setup:
    image: mongo
    depends_on:
      - db
    restart: on-failure
    entrypoint: [
        'bash',
        '-c',
        # This will try to initiate the replica set, until it succeeds twice (i.e. until the replica set is already initialized)
        'mongosh --host db:27017 --eval ''try {rs.initiate();} catch (err) { if(err.codeName !== "AlreadyInitialized") throw err };'''
      ]

volumes:
  db-data:
